<template>
  <div>
    <el-row v-show="chapterItem.name" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <h4 style="margin: 12px">{{ chapterItem.name }}</h4>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['admin:sysRole:edit']"
          type="text"
          style="font-size: 20px"
          icon="el-icon-edit"
          @click="editChapter(chapterKey,'edit')"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['admin:sysRole:remove']"
          type="text"
          style="font-size: 20px"
          icon="el-icon-delete"
          @click="editChapter(chapterKey,'delete')"
        />
      </el-col>
    </el-row>
    <el-table :data="chapterData.children" border>
      <el-table-column label="序号" prop="id" width="80" />
      <el-table-column
        v-for="(item,index) in chapterTable.columns"
        :key="index"
        :label="item.label"
        :prop="item.prop"
        :width="item.prop === 'date'?400:null"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.is_show === 1">
            <el-date-picker
              v-if="item.prop === 'date'"
              v-model="chapterTable.sel.date"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 95%"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
            <el-input v-else v-model="chapterTable.sel[item.prop]" placeholder="请输入内容" />
          </div>
          <div v-else>
            <span>{{ scope.row[item.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template slot-scope="scope">
          <el-button type="text" @click="editRow(scope.row,scope.$index)">编辑</el-button>
          <el-button type="text" @click="saveRow(scope.row,scope.$index)">保存</el-button>
          <el-button type="text" @click="deleteRow(scope.$index,chapterData.children)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="addsonchapter" @click="addSonchapter()">
      <i class="el-icon-plus" />添加子章节
    </div>
    <Exercises :visible="visible" @cancel="cancel" @submitForm="submitForm" />
  </div>
</template>

<script>
import { delSections } from '@/api/admin/sys-course'
import { chooseExercises } from '@/api/admin/sys-question'
import Exercises from '@/components/Exercises'
export default {
  name: 'Chapter',
  components: {
    Exercises
  },
  props: {
    chapterItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    chapterKey: {
      type: Number,
      default: () => {
        return null
      }
    },
    host: {
      type: String,
      default: () => {
        return ''
      }
    },
    headers: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chapterTable: {
        sel: null, // 选中行
        columns: [
          {
            prop: 'name',
            label: '子章节名称'
          },
          {
            prop: 'url',
            label: '直播地址'
          },
          {
            prop: 'date',
            label: '时间'
          }
        ]
      },
      chapterData: {
        children: []
      },
      coursewareUrl: null,
      coursewareName: null,
      visible: false,
      sectionsId: null
    }
  },
  created() {
    this.chapterData = { ...this.chapterItem }
  },
  methods: {
    choiceQuestion(event) {
      event.stopPropagation()
    },
    // 新增子章节
    addSonchapter() {
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      const j = {
        name: '',
        url: '',
        date: '',
        is_show: 1
      }
      this.chapterData.children.push(j)
      this.chapterTable.sel = JSON.parse(JSON.stringify(j))
    },
    saveRow(row, index) {
      // 保存
      const data = JSON.parse(JSON.stringify(this.chapterTable.sel))
      const dataList = {
        ...data,
        date: data.date.join('---')
      }
      for (const k in dataList) {
        row[k] = dataList[k] // 将sel里面的value赋值给这一行。ps(for....in..)的妙用，细心的同学发现这里我并没有循环对象row
      }
      row.is_show = -1
      //   if (data.id) {
      //     editChapter({
      //       ...data,
      //       is_show: -1,
      //       course_id: this.chapterData.course_id
      //     }).then(response => {
      //       row.is_show = -1;
      //       this.$emit("say", this.chapterData);
      //     });
      //   } else if (this.chapterData.id) {
      //     const sections = {
      //       ...this.chapterData.children[index],
      //       is_show: -1,
      //       pid: this.chapterData.id,
      //       course_id: this.chapterData.course_id
      //     };
      //     addChapter(sections).then(res => {
      //       if (res.code === 200) {
      //         row.is_show = -1;
      //         this.chapterData.children[index].id = res.data;
      //         this.$emit("say", this.chapterData);
      //       }
      //     });
      //   }
    },
    editRow(row) {
      // 编辑
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      this.chapterTable.sel = {
        ...row,
        date: [new Date('2000-11-10 10:10:00'), new Date('2000-11-10 10:10:00')]
      }
      row.is_show = 1
      this.$emit('say', this.chapterData)
    },
    deleteRow(index, rows) {
      // 删除
      const deleteData = rows.find((v, i) => i === index)
      if (deleteData.id) {
        this.$confirm('是否确认删除', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delSections({ ids: [deleteData.id] }).then(response => {
              rows.splice(index, 1)
              this.$emit('say', this.chapterData)
            })
          })
          .catch(function() {})
      }
    },
    editChapter(key, type) {
      const payload = {
        chapterItem: this.chapterData,
        chapterKey: key,
        type
      }
      this.$emit('dialogVisible', payload)
    },
    handleSuccess(res) {
      this.chapterTable.sel.url = res.data.full_path
      this.chapterTable.sel.url_name = res.data.name
    },
    addExercises(id) {
      this.visible = true
      this.sectionsId = id
    },
    cancel() {
      this.visible = false
    },

    submitForm(ids) {
      const parmars = {
        link_id: this.chapterItem.course_id,
        chapter_id: this.sectionsId,
        link_type: 3,
        question_bank_str: ids
      }
      chooseExercises(parmars).then(res => {
        this.visible = false
        const { children } = this.chapterData
        const childrens = children.map(item => {
          if (item.id === this.sectionsId) {
            return { ...item, is_contain_exercise: 1 }
          }
          return item
        })
        this.chapterData = {
          ...this.chapterData,
          children: childrens
        }
      })
    }
  }
}
</script>

<style>
.addsonchapter {
  border: 1px solid #c0c4cc;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  color: #3d64d4;
}
</style>
